/**
 * @description uuid
 * @return {String}
 */
export function uuid() {
  let d = new Date().getTime()
  const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
    /[xy]/g,
    function (c) {
      const r = (d + Math.random() * 16) % 16 | 0
      d = Math.floor(d / 16)
      return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)
    }
  )
  return uuid
}
/**
 * 延时指定的时间后执行回调函数
 * @param {number} delay - 延时时间（毫秒）
 * @returns {Promise} - 返回一个Promise对象
 */
export function delay(delay) {
  return new Promise((resolve) => {
    setTimeout(resolve, delay)
  })
}
/**
 * @description 转换对象为url参数
 * @return url参数字符串
 */
export function encodeParams(params, isPrefix = true) {
  const prefix = isPrefix ? '?' : ''
  const _result = []
  for (const key in params) {
    const value = params[key]
    // 去掉为空的参数
    if (['', undefined, null].includes(value)) {
      continue
    }
    if (value.constructor === Array) {
      value.forEach((_value) => {
        _result.push(
          encodeURIComponent(key) + '[]=' + encodeURIComponent(_value)
        )
      })
    } else {
      _result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
    }
  }
  return _result.length ? prefix + _result.join('&') : ''
}
/**
 * @description 对象深度克隆
 * @param {Object} obj 克隆对象
 * @return {Object}
 */
export function clone(obj) {
  // 对常见的“非”值，直接返回原来值
  if ([null, undefined, NaN, false].includes(obj)) return obj
  if (typeof obj !== 'object' && typeof obj !== 'function') {
    //原始类型直接返回
    return obj
  }
  var o = Array.isArray(obj) ? [] : {}
  for (const i in obj) {
    // eslint-disable-next-line no-prototype-builtins
    if (obj.hasOwnProperty(i)) {
      o[i] = typeof obj[i] === 'object' ? clone(obj[i]) : obj[i]
    }
  }
  return o
}

/**
 * @description 对象深度合并
 * @param {Object} target 目标对象
 * @param {Object} source 源对象
 * @return {Object}
 */
export function merge(target = {}, source = {}) {
  target = clone(target)
  if (typeof target !== 'object' || typeof source !== 'object') return false
  for (var prop in source) {
    // eslint-disable-next-line no-prototype-builtins
    if (!source.hasOwnProperty(prop)) continue
    if (prop in target) {
      if (typeof target[prop] !== 'object') {
        target[prop] = source[prop]
      } else {
        if (typeof source[prop] !== 'object') {
          target[prop] = source[prop]
        } else {
          if (target[prop]?.concat && source[prop]?.concat) {
            target[prop] = target[prop].concat(source[prop])
          } else {
            target[prop] = merge(target[prop], source[prop])
          }
        }
      }
    } else {
      target[prop] = source[prop]
    }
  }
  return target
}
